<template>
  <div class="icon-list">
    <div class="icon-list-header">
      <el-input
        v-model="searchQuery"
        placeholder="搜索图标名称"
        prefix-icon="Search"
        clearable
        class="search-input"
        @input="filterIcons"
      />
      <el-button type="primary" @click="loadIcons">刷新</el-button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>


    <!-- 图标网格 -->
    <div v-else class="icon-grid">
      <!-- 上传新图标 item -->
      <div class="icon-item upload-item" @click="handleUploadClick">
        <div class="icon-image-container upload-container">
          <el-icon :size="40" class="upload-icon"><Plus /></el-icon>
        </div>
        <div class="icon-info">
          <div class="icon-name">上传新图标</div>
        </div>
      </div>
      
      <!-- 现有图标 items -->
      <div
        v-for="icon in filteredIcons"
        :key="icon.id"
        class="icon-item"
        @click="emitIconClicked(icon)"
      >
        <div class="icon-image-container">
          <img :src="getIconUrl(icon.file_path)" :alt="icon.filename" class="icon-image" />
        </div>
        <div class="icon-info">
          <div class="icon-name" :title="icon.filename">{{ icon.filename }}</div>
          <div class="icon-actions">
            <el-button
              size="small"
              type="primary"
              @click.stop="editIcon(icon)"
            >
              编辑
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click.stop="confirmDelete(icon)"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页器 -->
    <el-pagination
      v-if="totalIcons > 0"
      background
      :current-page="currentPage"
      :page-size="pageSize"
      layout="prev, pager, next, total"
      :total="totalIcons"
      @current-change="handlePageChange"
      class="pagination"
    />

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑图标名称"
      width="30%"
    >
      <el-input v-model="editForm.filename" placeholder="请输入图标名称" />
      <template #footer>
        <span>
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateIconName" :loading="updating">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="30%"
    >
      <p>确定要删除图标 <strong>{{ iconToDelete?.filename }}</strong> 吗？此操作不可撤销。</p>
      <template #footer>
        <span>
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteConfirmed" :loading="deleting">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import footballService from '../services/footballService';

const props = defineProps({
  iconType: {
    type: String,
    required: true,
    validator: (val) => ['team', 'match'].includes(val)
  }
});

const emit = defineEmits([
  'icon-updated', 
  'icon-deleted', 
  'upload-clicked',
  'icon-clicked'
]);

// 数据状态
const icons = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(20);
const totalIcons = ref(0);
const searchQuery = ref('');

// 编辑状态
const editDialogVisible = ref(false);
const editForm = ref({ id: null, filename: '' });
const updating = ref(false);

// 删除状态
const deleteDialogVisible = ref(false);
const iconToDelete = ref(null);
const deleting = ref(false);

// 过滤后的图标列表
const filteredIcons = computed(() => {
  if (!searchQuery.value) return icons.value;
  
  const query = searchQuery.value.toLowerCase();
  return icons.value.filter(icon => 
    icon.filename.toLowerCase().includes(query)
  );
});

// 加载图标列表
const loadIcons = async () => {
  loading.value = true;
  
  try {
    const result = await footballService.getIcons(props.iconType, currentPage.value, pageSize.value);
    
    if (result.success) {
      icons.value = result.data.items || [];
      totalIcons.value = result.data.total || 0;
    } else {
      ElMessage.error(result.message || '加载图标失败');
    }
  } catch (error) {
    console.error('加载图标失败:', error);
    ElMessage.error('加载图标时发生错误');
  } finally {
    loading.value = false;
  }
};

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  loadIcons();
};

// 获取图标URL
const getIconUrl = (path) => {
  return path;
};

// 点击上传按钮
const handleUploadClick = () => {
  emit('upload-clicked');
};

// 点击图标
const emitIconClicked = (icon) => {
  emit('icon-clicked', icon);
};

// 编辑图标
const editIcon = (icon) => {
  editForm.value = {
    id: icon.id,
    filename: icon.filename
  };
  editDialogVisible.value = true;
};

// 更新图标名称
const updateIconName = async () => {
  if (!editForm.value.filename.trim()) {
    ElMessage.warning('图标名称不能为空');
    return;
  }
  
  updating.value = true;
  
  try {
    const result = await footballService.updateIconFilename(editForm.value.id, editForm.value.filename);

    if (result.success) {
      ElMessage.success('图标名称更新成功');
      emit('icon-updated');
      editDialogVisible.value = false;
      
      // 更新本地数据
      const index = icons.value.findIndex(i => i.id === editForm.value.id);
      if (index !== -1) {
        icons.value[index].filename = editForm.value.filename;
      }
    } else {
      console.error('更新图标名称失败:', result.message);
      ElMessage.error(result.message || '更新图标名称失败');
    }
  } catch (error) {
    ElMessage.error(error.response.data.message);
  } finally {
    updating.value = false;
  }
};

// 确认删除
const confirmDelete = (icon) => {
  iconToDelete.value = icon;
  deleteDialogVisible.value = true;
};

// 确认删除操作
const deleteConfirmed = async () => {
  if (!iconToDelete.value) return;
  
  deleting.value = true;
  
  try {
    const result = await footballService.deleteIcon(iconToDelete.value.id);
    
    if (result.success) {
      ElMessage.success('图标删除成功');
      emit('icon-deleted');
      deleteDialogVisible.value = false;
      
      // 更新本地数据
      icons.value = icons.value.filter(i => i.id !== iconToDelete.value.id);
    } else {
      ElMessage.error(result.message || '删除图标失败');
    }
  } catch (error) {
    console.error('删除图标失败:', error);
    ElMessage.error('删除图标时发生错误');
  } finally {
    deleting.value = false;
  }
};

// 过滤图标
const filterIcons = () => {
  // 实际过滤逻辑由计算属性 filteredIcons 处理
};

// 监听图标类型变化
watch(() => props.iconType, () => {
  currentPage.value = 1;
  loadIcons();
},
{ immediate: true });
</script>

<style scoped>
.icon-list {
  width: 100%;
  height: calc(90vh - 180px);
}

.icon-list-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-input {
  width: 250px;
}

.loading-container, .empty-state {
  padding: 40px 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.icon-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 5px;
  margin-bottom: 20px;
}

.icon-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.3s;
  background: white;
  cursor: pointer;
}

.icon-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-5px);
}

.upload-item {
  border: 1px dashed #d9d9d9;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.upload-item:hover {
  border-color: #409eff;
}

.upload-container {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.upload-icon {
  color: #909399;
}

.icon-image-container {
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
}

.icon-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.icon-info {
  padding: 5px;
}

.icon-name {
  font-weight: 500;
  font-size: 14px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-bottom: 10px;
  text-align: center;
}

.icon-actions {
  display: flex;
  justify-content: space-between;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>